<?php

/**
 * Addshift Function
 *
 * Add a new shift
 *
 * @author Max Sibbald <maxsibbald@gmail.com>
 */
include_once 'UTerrorcode.php';
include_once 'UTcheckAuth.php';
include_once 'UTDBGlobal.php';

/**
 * @param $authUser string
 * @param $authUserPass string
 * @param $arrayOfData string
 * @return array
 */
function addShift($authUser, $authUserPass, $arrayOfData) {
   global $dbaddress;
   global $dbuser;
   global $dbpassword;
   global $dbdatabasename;

   if (checkAuthentication($authUser, $authUserPass) != true) {
      return array(ErrorCode::authFailRead);
   }

   $conn = mysqli_connect($dbaddress, $dbuser, $dbpassword, $dbdatabasename);
   if (!$conn) {
      die('Could not connect: ' . mysqli_error());
      return array(ErrorCode::sysError);
   }

   //get the empID
   $presql = "SELECT empID FROM paradigmshift_dev.Account WHERE accName = '" . $arrayOfData['accName'] . "' LIMIT 1";
   $result = mysqli_query($conn, $presql);
   if ($result) {
      $row = mysqli_fetch_row($result);
      $empID = $row[0];
   } else {
      return array(ErrorCode::failCreate + 700);
   }

   //try to get the dateID
   $dateID;
   $presql = "SELECT dateID FROM paradigmshift_dev.Dates WHERE datestamp = '" . $arrayOfData['datestamp'] . "' LIMIT 1";
   $result = mysqli_query($conn, $presql);
   if ($result->num_rows > 0) {
      $row = mysqli_fetch_row($result);
      $dateID = $row[0];
   } else {
      //date entry does not exist yet so create one
      //get the max date and increment
      $presql = "SELECT MAX(dateID) FROM paradigmshift_dev.Dates";
      $result = mysqli_query($conn, $presql);
      $row = mysqli_fetch_row($result);
      $dateID = $row[0] + 1;

      $presql = "INSERT INTO paradigmshift_dev.Dates (dateID, datestamp) VALUES($dateID, '" . $arrayOfData['datestamp'] . "')";
      mysqli_query($conn, $presql);
   }
   if ($arrayOfData['endTime'] == NULL) {
      $sql = "INSERT INTO RoleDate (roleID, empID, dateID, startTime, shiftStatus) VALUES (" . $arrayOfData['roleID'] . "," . $empID . "," . $dateID . ",'" . $arrayOfData['startTime'] . "','Occupied');";
   } else {
      $sql = "INSERT INTO RoleDate (roleID, empID, dateID, startTime, endTime, shiftStatus) VALUES (" . $arrayOfData['roleID'] . "," . $empID . "," . $dateID . ",'" . $arrayOfData['startTime'] . "','" . $arrayOfData['endTime'] . "','Occupied');";
   }
   if (mysqli_query($conn, $sql)) {
      mysqli_close($conn);
      return array(ErrorCode::successCreate);
   } else {
      mysqli_close($conn);
      return array(ErrorCode::failCreate);
   }
}

?>